package com.ruoyi.system.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.CruxDevicePosition;
import com.ruoyi.system.domain.vo.PreventionCheckTaskConfigCountVO;
import com.ruoyi.system.domain.vo.PreventionCheckTaskCountVO;
import com.ruoyi.system.domain.vo.PreventionHiddenRegisterCountVO;
import com.ruoyi.system.entity.*;
import com.ruoyi.system.mapper.PreventionAlertMapper;
import com.ruoyi.system.mapper.PreventionDeviceMapper;
import com.ruoyi.system.mapper.PreventionHiddenRegisterMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.PreventionHiddenRegisterService;
import com.ruoyi.system.service.SysActingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 隐患录入记录表(PreventionHiddenRegister)表服务实现类
 * @since 2022-11-22 17:20:34
 */
@Service("preventionHiddenRegisterService")
public class PreventionHiddenRegisterServiceImpl implements PreventionHiddenRegisterService {
    @Resource
    private PreventionHiddenRegisterMapper preventionHiddenRegisterDao;

    @Resource
    private SysActingService sysActingService;

    @Resource
    private PreventionAlertMapper preventionAlertMapper;

    @Resource
    private PreventionDeviceMapper preventionDeviceMapper;

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private EnterpriseWXServiceImpl enterpriseWXService;

    @Autowired
    private RedisCache redisCache;
    /**
     * 通过ID查询单条数据
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public PreventionHiddenRegister queryById(Integer id) {
        return this.preventionHiddenRegisterDao.queryById(id);
    }

    /**
     * 分页查询
     * @return 查询结果
     */
    @Override
    public List<PreventionHiddenRegister> queryByPage(PreventionHiddenRegister preventionHiddenRegister) {
        return preventionHiddenRegisterDao.queryAllByLimit(preventionHiddenRegister);
    }

    /**
     * 分页查询
     * @return 查询结果
     */
    @Override
    public List<PreventionHiddenRegister> queryHiddenList(PreventionHiddenRegister preventionHiddenRegister) {
        return preventionHiddenRegisterDao.queryHiddenList(preventionHiddenRegister);
    }

    /**
     * 新增数据
     * @param preventionHiddenRegister 实例对象
     * @return 实例对象
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public PreventionHiddenRegister insert(PreventionHiddenRegister preventionHiddenRegister) {
        if (preventionHiddenRegister.getHiddenSource().equals("三录入")) {
            preventionHiddenRegister.setHiddenProgress("待修改");
            preventionHiddenRegister.setHiddenState(3);
            this.preventionHiddenRegisterDao.insert(preventionHiddenRegister);
            return preventionHiddenRegister;
        }
        preventionHiddenRegister.setRegisterUserId(SecurityUtils.getUserId().intValue());
        preventionHiddenRegister.setRegisterUserName(SecurityUtils.getUsername());
        this.preventionHiddenRegisterDao.insert(preventionHiddenRegister);
        // 添加审核待办
        SysActing sysActing = new SysActing();
        sysActing.setTitleName("隐患");
        sysActing.setTitleType("审核");
        sysActing.setTitleInfo(preventionHiddenRegister.getHiddenCheckType());
        sysActing.setExecutorName(preventionHiddenRegister.getRectificationUserName());
        sysActing.setExecutorId(preventionHiddenRegister.getRectificationUserId());
        sysActing.setSourceId(preventionHiddenRegister.getId());
        sysActing.setOriginatorId(preventionHiddenRegister.getRegisterUserId());
        sysActing.setOriginatorName(preventionHiddenRegister.getRegisterUserName());
        sysActingService.insert(sysActing);
        sengwx(1,preventionHiddenRegister.getRectificationUserId(),preventionHiddenRegister);
        return preventionHiddenRegister;
    }

    /**
     * 修改数据
     * @param preventionHiddenRegister 实例对象
     * @return 实例对象
     */
    @Override
    public PreventionHiddenRegister update(PreventionHiddenRegister preventionHiddenRegister) {
        if (preventionHiddenRegister.getHiddenSource().equals("三录入") && preventionHiddenRegister.getHiddenProgress().equals("待修改") || preventionHiddenRegister.getHiddenProgress().equals("已驳回") || preventionHiddenRegister.getHiddenProgress().equals("待审核")) {
            preventionHiddenRegister.setRegisterUserId(SecurityUtils.getUserId().intValue());
            preventionHiddenRegister.setRegisterUserName(SecurityUtils.getUsername());
            preventionHiddenRegister.setHiddenState(0);
            preventionHiddenRegister.setHiddenProgress("待审核");
            // 添加审核待办
            SysActing sysActing = new SysActing();
            sysActing.setTitleName("隐患");
            sysActing.setTitleType("审核");
            sysActing.setTitleInfo(preventionHiddenRegister.getHiddenCheckType());
            sysActing.setExecutorName(preventionHiddenRegister.getRectificationUserName());
            sysActing.setExecutorId(preventionHiddenRegister.getRectificationUserId());
            sysActing.setSourceId(preventionHiddenRegister.getId());
            sysActing.setOriginatorId(preventionHiddenRegister.getRegisterUserId());
            sysActing.setOriginatorName(preventionHiddenRegister.getRegisterUserName());
            sysActingService.insert(sysActing);
            sengwx(1,preventionHiddenRegister.getRectificationUserId(),preventionHiddenRegister);
        }
        this.preventionHiddenRegisterDao.update(preventionHiddenRegister);
        return this.queryById(preventionHiddenRegister.getId());
    }

    /**
     * 通过主键删除数据
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.preventionHiddenRegisterDao.deleteById(id) > 0;
    }

    @Override
    public Map<String, List<Map<String, Object>>> countHidden(Integer deptId,String level) {
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        // 根据进度统计隐患数量
        String[] arr = new String[]{"待审核","待整改","待复核","已完成"};
        List<Map<String, Object>> progressMap = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            Map<String, Object> countProgress = preventionHiddenRegisterDao.countProgress(deptId, level, arr[i]);
            if (CollUtil.isEmpty(countProgress)) {
                countProgress = new HashMap<>();
                countProgress.put("hidden_progress",arr[i]);
                countProgress.put("count",0);
                progressMap.add(countProgress);
            } else {
                progressMap.add(countProgress);
            }
        }
        map.put("hidden",progressMap);
        // 查询排查任务
        List<Map<String, Object>> taskMap = preventionHiddenRegisterDao.countTask(deptId,level);
        map.put("task",taskMap);
        return map;
    }

    /**
     *  流转
     * @param preventionHiddenRegister
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRectificationUserName(PreventionHiddenRegister preventionHiddenRegister) {
        Long userId = SecurityUtils.getUserId();
        Integer id = preventionHiddenRegister.getId();
        PreventionHiddenRegister byId = preventionHiddenRegisterDao.queryById(id);
        if (byId.getRectificationUserId() != userId.intValue() && userId != 1) {
            throw new ServiceException("当前隐患只允许整改责任人可以流转",500);
        }
        if (!byId.getHiddenProgress().equals("待整改")) {
            throw new ServiceException("当前状态不是待整改状态，无法流转",500);
        }
        preventionHiddenRegisterDao.update(preventionHiddenRegister);
        preventionHiddenRegister = preventionHiddenRegisterDao.queryById(preventionHiddenRegister.getId());
        // 修改待办执行人
        SysActing sysActing = new SysActing();
        sysActing.setTitleName("隐患");
        sysActing.setTitleType("整改");
        sysActing.setSourceId(preventionHiddenRegister.getId());
        sysActing.setExecutorName(preventionHiddenRegister.getRectificationUserName());
        sysActing.setExecutorId(preventionHiddenRegister.getRegisterUserId());
        sysActingService.updateExecutorUser(sysActing);
    }

    /**
     *  隐患整改完成---添加复核待办提醒
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRectification(PreventionHiddenRegister param) {
        PreventionHiddenRegister preventionHiddenRegister = preventionHiddenRegisterDao.queryById(param.getId());
        Integer userId = SecurityUtils.getUserId().intValue();
        if (!userId.equals(preventionHiddenRegister.getRectificationUserId())) {
            throw new ServiceException("您无权操作此条隐患记录",500);
        }
        if (!preventionHiddenRegister.getHiddenProgress().equals("待整改")) {
            throw new ServiceException("当前状态不是待整改状态，无法整改",500);
        }
        param.setHiddenCompleteTime(DateUtil.now());
        param.setHiddenProgress("待复核");
        preventionHiddenRegisterDao.update(param);
        // 完成整改待办
        sysActingService.completeActing("隐患","整改",preventionHiddenRegister.getId());
        // 创建复核待办
        SysActing sysActing = new SysActing();
        sysActing.setTitleName("隐患");
        sysActing.setTitleType("复核");
        sysActing.setTitleInfo(preventionHiddenRegister.getHiddenCheckType());
        sysActing.setExecutorName(preventionHiddenRegister.getReviewUserName());
        sysActing.setExecutorId(preventionHiddenRegister.getReviewUserId());
        sysActing.setSourceId(preventionHiddenRegister.getId());
        sysActing.setOriginatorId(preventionHiddenRegister.getRegisterUserId());
        sysActing.setOriginatorName(preventionHiddenRegister.getRegisterUserName());
        sysActingService.insert(sysActing);
    }

    /**
     *  隐患复核完成 --- 完成隐患待办任务
     * @param param
     */
    @Override
    public void updateReview(PreventionHiddenRegister param) {
        PreventionHiddenRegister preventionHiddenRegister = preventionHiddenRegisterDao.queryById(param.getId());
        Integer userId = SecurityUtils.getUserId().intValue();
        if (!userId.equals(preventionHiddenRegister.getReviewUserId())) {
            throw new ServiceException("您无权操作此条隐患记录",500);
        }
        preventionHiddenRegister.setHiddenReviewTime(DateUtil.now());
        preventionHiddenRegister.setHiddenProgress("已完成");
        preventionHiddenRegister.setHiddenReviewInfo(param.getHiddenReviewInfo());
        preventionHiddenRegisterDao.update(preventionHiddenRegister);
        sysActingService.completeActing("隐患","复核",preventionHiddenRegister.getId());
    }

    /**
     *  审核
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String updateHiddenState(PreventionHiddenRegister param) {
        PreventionHiddenRegister preventionHiddenRegister = preventionHiddenRegisterDao.queryById(param.getId());
        Integer userId = SecurityUtils.getUserId().intValue();
        //Integer userId = param.getTokenId();
        if (null ==userId){
            throw new ServiceException("当前用户信息不存在",601);
        }
        if (userId != 1) {
            if (!userId.equals(preventionHiddenRegister.getRectificationUserId())) {
                throw new ServiceException("您无权操作此条隐患记录",500);
            }
        }
        if (param.getHiddenState() == 1) {
            param.setHiddenProgress("待整改");
        } else {
            param.setHiddenProgress("已驳回");
        }
        int update = preventionHiddenRegisterDao.update(param);
        if (1 !=update){
            throw new ServiceException("审核失败",500);
        }
        // 审核完成-完成待办任务-待整改状态-创建整改待办提醒
        sysActingService.completeActing("隐患","审核",preventionHiddenRegister.getId());
        if (param.getHiddenState() == 1) {
            SysActing sysActing = new SysActing();
            sysActing.setTitleName("隐患");
            sysActing.setTitleType("整改");
            sysActing.setTitleInfo(preventionHiddenRegister.getHiddenCheckType());
            sysActing.setExecutorName(preventionHiddenRegister.getRectificationUserName());
            sysActing.setExecutorId(preventionHiddenRegister.getRectificationUserId());
            sysActing.setSourceId(preventionHiddenRegister.getId());
            sysActing.setOriginatorId(preventionHiddenRegister.getRegisterUserId());
            sysActing.setOriginatorName(preventionHiddenRegister.getRegisterUserName());
            sysActingService.insert(sysActing);
        }
        return "操作成功";
    }

    // 定时检查隐患是否超时或是否临期
    @Scheduled(cron = "0/60 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void scheduledCheck() {
        List<PreventionHiddenRegister> preventionHiddenRegisters = preventionHiddenRegisterDao.queryAllByLimit(new PreventionHiddenRegister());
        for (PreventionHiddenRegister preventionHiddenRegister : preventionHiddenRegisters) {
            if (preventionHiddenRegister.getHiddenProgress().equals("已超时")) {
                continue;
            }
            if (preventionHiddenRegister.getHiddenProgress().equals("已完成")) {
                continue;
            }
            PreventionDevice preventionDevice = preventionDeviceMapper.queryById(preventionHiddenRegister.getDeviceId());
            String rectificationEndTime = preventionHiddenRegister.getRectificationEndTime();
            DateTime parse = DateUtil.parse(rectificationEndTime, "yyyy-MM-dd");
            String today = DateUtil.today();
            DateTime parse1 = DateUtil.parse(today, "yyyy-MM-dd");
            // 任务结束时间大于当前时间为true
            boolean after = parse1.after(parse);
            if (after) {
                // 超时处理
                preventionHiddenRegister.setHiddenProgress("已超时");
                PreventionAlert preventionAlert = new PreventionAlert();
                preventionAlert.setAlertType("隐患治理");
                preventionAlert.setAlertLevel(preventionDevice.getDeviceName());
                preventionAlert.setAlertInfo("隐患整改已结束，未完成整改");
                preventionAlert.setAlertTaskUser(preventionHiddenRegister.getRectificationUserName());
                preventionAlert.setAlertContent(preventionHiddenRegister.getHiddenInfo());
                preventionAlert.setAlertEndTime(rectificationEndTime);
                preventionAlert.setAlertNoticeState("0");
                preventionAlert.setAlertNoticeName("隐患闭环推送人员");
                preventionAlert.setAlertNoticeMode("企业微信");
                preventionAlertMapper.insert(preventionAlert);
                preventionHiddenRegisterDao.update(preventionHiddenRegister);
                sengwx(3,preventionHiddenRegister.getRectificationUserId(),preventionHiddenRegister);
            } else {
                // 是否临期处理
                long betweenDay = DateUtil.between(parse, parse1, DateUnit.DAY);
                if (betweenDay == 0) {
                    PreventionAlert preventionAlert = new PreventionAlert();
                    preventionAlert.setAlertType("隐患治理");
                    preventionAlert.setAlertLevel(preventionDevice.getDeviceName());
                    preventionAlert.setAlertInfo("隐患整改临近整改结束日期，请尽快整改");
                    preventionAlert.setAlertTaskUser(preventionHiddenRegister.getRectificationUserName());
                    preventionAlert.setAlertContent(preventionHiddenRegister.getHiddenInfo());
                    preventionAlert.setAlertEndTime(rectificationEndTime);
                    preventionAlert.setAlertNoticeState("0");
                    preventionAlert.setAlertNoticeName("隐患闭环推送人员");
                    preventionAlert.setAlertNoticeMode("企业微信");
                    long count = preventionAlertMapper.count(preventionAlert);
                    if (count == 0) {
                        preventionAlertMapper.insert(preventionAlert);
                        sengwx(2,preventionHiddenRegister.getRectificationUserId(),preventionHiddenRegister);
                    }
                }
            }
        }
    }


    @Override
    public List<PreventionCheckTaskCountVO> getHiddenDayTemp(String weekTo) {
        return preventionHiddenRegisterDao.getHiddenDayTemp(weekTo);
    }

    @Override
    public List<PreventionCheckTaskCountVO> getHiddenMeekTemp(String weekStart,String weekEnd) {
        return preventionHiddenRegisterDao.getHiddenMeekTemp(weekStart,weekEnd);
    }

    @Override
    public List<PreventionCheckTaskCountVO> getHiddenMonthTemp(String monthTo) {
        return preventionHiddenRegisterDao.getHiddenMonthTemp(monthTo);
    }

    @Override
    public List<PreventionCheckTaskCountVO> getAllHidden() {
        return preventionHiddenRegisterDao.getAllHidden();
    }


    /**
     * 隐患清单_全部数据_分页查询
     * @return 查询结果
     */
    @Override
    public List<PreventionHiddenRegister> getHiddenListPage(PreventionHiddenRegister preventionHiddenRegister) {
        return preventionHiddenRegisterDao.getHiddenListPage(preventionHiddenRegister);
    }

    @Override
    public int getDzgyh(String checkUserName) {
        return preventionHiddenRegisterDao.getDzgyh(checkUserName) ;
    }

    @Override
    public List<PreventionCheckTaskConfigCountVO> getToCountHiddenRemind(String checkUserName) {
        return preventionHiddenRegisterDao.getToCountHiddenRemind(checkUserName);
    }

    @Override
    public List<PreventionCheckTaskConfigCountVO> getToCountHiddenCondition(String checkUserName) {
        return preventionHiddenRegisterDao.getToCountHiddenCondition(checkUserName);
    }

    /**
     *
     * @return
     */
    @Override
    public List<PreventionCheckTaskConfigCountVO> getToCountDeptHiddenPC(PreventionHiddenRegisterCountVO preventionHiddenRegisterCountVO) {
        return preventionHiddenRegisterDao.getToCountDeptHiddenPC(preventionHiddenRegisterCountVO);
    }

    @Override
    public List<PreventionCheckTaskConfigCountVO> getToCountDeptHiddenZG(PreventionHiddenRegisterCountVO preventionHiddenRegisterCountVO) {
        return preventionHiddenRegisterDao.getToCountDeptHiddenZG(preventionHiddenRegisterCountVO);
    }

    @Override
    public List<PreventionCheckTaskConfigCountVO> getToCountHiddenDeptAll() {
        return preventionHiddenRegisterDao.getToCountHiddenDeptAll();
    }

    @Override
    public List<PreventionHiddenRegister> queryAll(PreventionHiddenRegister preventionHiddenRegister) {
        return preventionHiddenRegisterDao.queryAll(preventionHiddenRegister);
    }

    @Override
    public List<PreventionCheckTaskConfigCountVO> getToCountDeptAll() {
        return preventionHiddenRegisterDao.getToCountDeptAll();
    }

    @Async
    public void sengwx(Integer type,Integer userId,PreventionHiddenRegister preventionHiddenRegister) {
        // 1-登记 2-临期 3-超期
        EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
        sendMessageRequest.setMsgtype("text");
        sendMessageRequest.setAgentid(1000319);
        EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
        List<Integer> userIds = sysUserMapper.selectUserByPostName("隐患闭环推送");
        Integer id = sysUserMapper.selectUserWXIdById(userId);
        if (type == 1) {
            userIds.add(id);
            sendMessageRequest.setTouser(CollUtil.join(userIds,"|"));
            messageContent.setContent("隐患登记提醒: (" + preventionHiddenRegister.getDeptName() + "-" + preventionHiddenRegister.getHiddenCheckUser() + "登记" + preventionHiddenRegister.getHiddenName() + ",请及时处理!)");
        } else if (type == 2) {
            userIds.add(id);
            sendMessageRequest.setTouser(CollUtil.join(userIds,"|"));
            messageContent.setContent("隐患整改临期提醒: (" + preventionHiddenRegister.getHiddenName() + " 即将在 " + preventionHiddenRegister.getRectificationEndTime() + " 超期,请及时处理!)");
        } else {
            sendMessageRequest.setTouser(CollUtil.join(userIds,"|"));
            messageContent.setContent("隐患整改超期预警: (" + preventionHiddenRegister.getHiddenName() + " 已逾期,请监督整改完成!)");
        }
        sendMessageRequest.setText(messageContent);
        enterpriseWXService.pushMessage(sendMessageRequest);
    }
}
